<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <Top @receive="receive"></Top>
        <List :todos="todos"
        ></List>
        <user-footer :todos="todos"
                     @changeCompleted="changeCompleted"
                     :clearAllTodo="clearAllTodo"
        ></user-footer>
      </div>
    </div>
  </div>
</template>

<script>
import Top from "@/components/Top";
import UserFooter from "@/components/UserFooter";
import List from "@/components/List";
export default {
  name: "JobList",
  components: {List, UserFooter, Top},
  data(){
    return {
      todos:JSON.parse(localStorage.getItem('todos')) || []
    }
  },
  methods:{
    receive(obj){
      this.todos.unshift(obj)
    },
    //勾线 or 取消勾线todo
    checkTodo(id){
      this.todos.forEach((todo)=>{
        if(todo.id===id) todo.completed= !todo.completed
      })
    },
    //删除某个位置的id
    deleteTodo(_,id){
      for(let i=0;i<this.todos.length;i++){
        if(this.todos[i].id===id) this.todos.splice(i,1)
      }
    },
    //将所有位置的completed改为true/false
    changeCompleted(e){
      this.todos.forEach((todo)=>{
        if(!todo.completed && e) todo.completed= !todo.completed
        if(todo.completed && !e) todo.completed= !todo.completed
      })
    },
    changeTitle(id,e){
      this.todos.forEach((todo)=>{
        if(todo.id===id){
          todo.title = e
        }
      })
    },
    //清除所有todo
    clearAllTodo(){
      this.todos = this.todos.filter((todo)=>{
        return !todo.completed
      })
    }
  },
  watch:{
    todos:{
      deep:true,
      handler(value){
        localStorage.setItem('todos',JSON.stringify(value))
      }
    }
  },
  mounted() {
    this.$bus.$on('checkTodo',this.checkTodo)
    // this.$bus.$on('deleteTodo',this.deleteTodo)
    this.pubId = pubsub.subscribe('deleteTodo',this.deleteTodo)
    this.$bus.$on('changeTitle',this.changeTitle)
  },
  beforeDestroy() {
    this.$bus.$off('checkTodo')
    this.unsubscribe(this.pubId)
    this.$bus.$off('changeTitle')
    // this.$bus.$off('deleteTodo')
  }
}
</script>

<style scoped>
/*  item*/
#root{
  color:#fff;
  margin-top: 20px;
  margin-left: 30px;
  display: flex;
  align-items: center;
  border: 5px solid green;
  justify-content: center;

}
li{
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}
li label{
  float: left;
  cursor: pointer;
}
li label li input{
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}
li button{
  float: right;
  display: none;
  margin-top: 3px;
}
li:before{
  content:initial;
}
li:last-child{
  border-bottom: none;
}
li:hover{
  background-color: #ddd;
}
li:hover button{
  display: block;
}
</style>